import React, { createContext, useEffect, useReducer, useState } from 'react';
import store from "store";
import { useHistory } from "react-router-dom";
import { getUserInfo } from "../apis/account";
import { Spin } from "antd";
import { S_MAN_TOKEN } from '../utils/constant';

export const UserContext = createContext({});

interface UserInfo {
  id?: string;
}

export const UserReducer = (userInfo: object, action: {
  type: string;
  data: object;
}) => {
  switch(action.type) {
    case "LOGIN_SUCCESS":
      return {
        ...userInfo,
        ...action.data
      }
  }
  return userInfo;
}

export const UserProvider = (props: any) => {
  const [userInfo, userDispatcher] = useReducer(UserReducer, {});
  const token = store.get(S_MAN_TOKEN);
  const history = useHistory();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (token && !(userInfo as UserInfo).id) {
      setLoading(true);
      getUserInfo().then((res: any) => {
        if (res && res.success) {
          userDispatcher({
            type: 'LOGIN_SUCCESS',
            data: res.data
          })
        }
      }).catch((err) => {
        history.push("/account/login")
      }).finally(() => {
        setLoading(false);
      })
    }
  }, [token])

  if (!token) {
    history.push("/account/login");
    return null;
  }

  if (loading) {
    return (
      <div className="full-spin">
        <Spin />
      </div>
    )
  }

  return (
    <UserContext.Provider value={{ userInfo, userDispatcher }}>
      {props.children}
    </UserContext.Provider>
  )
}